/**查找分页控件 -> 请求下一页 -> 增删元素 -> 加载在页面 */
async function loadNextPage() {
  let [lastNrPage] = [...document.getElementsByClassName('page_chapter')].slice(-1)
  let url = lastNrPage.querySelector('li:nth-child(3) a').href

  const response = await fetch(url)

  let host = window.location.host
  let isUseGbk = ['www.23xsww.cc', 'www.blqukk.cc', 'www.123vvxw.cc', 'www.yqxsg.cc'].includes(host)

  const decoder = new TextDecoder(isUseGbk ? 'gbk' : 'utf8')
  const html = decoder.decode(await response.arrayBuffer())
  let div = document.createElement('div')
  div.innerHTML = html

  let alink = document.createElement('a')
  alink.href = url
  alink.innerText = '本页'
  let li = document.createElement('li')
  li.appendChild(alink)
  let pageDom = div.querySelector('.page_chapter ul')
  pageDom.insertBefore(li, pageDom.children[3])
  pageDom.removeChild(pageDom.children[4])

  div.querySelector('.book').style.borderLeftWidth = '0'
  div.querySelector('.book').style.borderRrightWidth = '0'
  div.querySelector('.book').style.borderBottomWidth = '0'

  let contentEl = div.getElementsByClassName('content')[0]
  if (contentEl) {
    let h1 = contentEl.querySelector('h1')
    let txt = contentEl.querySelector('#content')
    let page = contentEl.querySelector('.page_chapter')

    contentEl.innerHTML = ''
    contentEl.appendChild(h1)
    contentEl.appendChild(txt)
    contentEl.appendChild(page)
  }

  $chromePlugin.cleanPage(div, ['.apprecom', '.ywtop', '.header', '.nav', '.path', '.content .link', '.center', '.footer'])

  let [lastContent] = [...document.getElementsByClassName('content')].slice(-1)
  lastContent.parentNode.appendChild(div)
  return { div, url }
}

/**从页面获取书名 */
function getBookName() {
  let dom = null
  let introduceEls = document.getElementsByClassName('book') || []
  if (!introduceEls.length) return ''
  let [introduceEl] = introduceEls
  dom = introduceEl.querySelector('h2')
  if (dom) {
    return dom.innerHTML
  }

  dom = introduceEl.querySelector('.p')
  if (!dom) return ''
  let len = dom.children.length
  let nameIndex = len == 4 ? 2 : 1
  return dom.children[nameIndex].innerHTML
}

/**_addObserver传入targetSelector、chapterTitleSelector*/
function addObserver(dom = document, url = location.href) {
  _addObserver('.content', '.content h1', dom, url)
}

/**去除广告 */
function filterAd() {
  let apprecomEls = document.getElementsByClassName('apprecom')
  apprecomEls && [...apprecomEls].forEach((el) => (el.style.display = 'none'))
}

$chromePlugin.loadQueueFn.push(filterAd)
